package com.example.controller.user;

import com.alibaba.dashscope.audio.tts.SpeechSynthesisAudioFormat;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.example.dto.SoundComDto;
import com.example.dto.SoundDto;
import com.example.dto.SoundPageQueryDto;
import com.example.dto.SoundPutDto;
import com.example.entity.Sound;
import com.example.properties.AliOssProperties;
import com.example.result.PageResult;
import com.example.result.Result;
import com.example.service.SoundService;
import com.example.utils.AliOssUtil;
import com.example.vo.SoundVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.alibaba.dashscope.audio.tts.SpeechSynthesisParam;
import com.alibaba.dashscope.audio.tts.SpeechSynthesizer;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.UUID;

import static java.lang.System.exit;

@RestController
@RequestMapping("/front/sound")
@Slf4j
public class SoundController {
    /*
     * 获取声音样本列表
     * */
    @Autowired
    private SoundService soundService;
    @Autowired
    private AliOssProperties aliOssProperties;
    @Autowired
    private AliOssUtil aliOssUtil;


    public Result<List<Sound>> getSoundList(SoundPageQueryDto soundPageQueryDto) {
        log.info("获取声音样本列表");
        PageResult pageResult = soundService.pageQuery(soundPageQueryDto);
        return Result.success(pageResult.getRecords());
    }
    @GetMapping("/getAllSound")
     public Result<List<Sound>> getAllSound(){
        log.info("获取声音样本列表");
        List<Sound> records =soundService.getAllSound();
       return  Result.success(records);
     }

    /*
     * 上传音频文件。*/
    @PostMapping("/saveOrUpdate")
    public Result upload( @RequestParam(value = "id", required = false) String id, // id 可选，用于更新
                          @RequestParam("name") String name,
                          @RequestParam("gender") String gender,
                          @RequestParam("language") String language,
                          @RequestParam("discription") String description,
                          @RequestParam(value = "audioFile", required = false) MultipartFile audioFile) throws NoApiKeyException, InputRequiredException, IOException {
        log.info("上传音频文件");
        if(id==null){
            String originalFilename = audioFile.getOriginalFilename();
           // String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String filename = UUID.randomUUID() + ".wav";
            String filepath = aliOssUtil.upload(audioFile.getBytes(), filename);
            SoundDto soundDto = SoundDto.builder()
                    .name(name)
                    .gender(gender)
                    .language(language)
                    .discription(description)
                    .audioUrl(filepath)
                    .build();
            soundService.upload(soundDto);
          log.info("文件上传成功");
            return Result.success();}
        else {
            SoundDto soundDto = SoundDto.builder()
                    .id(Long.valueOf(id))
                    .name(name)
                    .gender(gender)
                    .language(language)
                    .discription(description)
                    .build();
            log.info("修改音频文件");
            soundService.update(soundDto);
        }

      return Result.success();
    }

    /*
     * 删除指定声音样本。
     * */
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        log.info("删除音频文件");
        soundService.deleteById(id);
        return Result.success();
    }

    /*
     * 修改指定声音样本。
     * */
    @PutMapping("/update")
    public Result update(@RequestBody SoundDto soundDto) {
        log.info("修改音频文件");
        soundService.update(soundDto);
        return Result.success();
    }

    /*
     * 根据id查询指定声音样本。
     * */
    @GetMapping("/{id}")
    public Result<SoundVo> getById(@PathVariable Integer id) {
        log.info("根据id查询指定声音样本");
        SoundVo soundvo = soundService.getById(id);
        return Result.success(soundvo);
    }

    @PostMapping("/voiceguide/generate-voice")
    public Result voiceSysCom(@RequestBody SoundPutDto soundPutDto) throws IOException {
        log.info("合成系统声音");
       String url = soundService.generate(soundPutDto);
        return Result.success(url);
    }

   /*  @PostMapping("com")
   public Result voiceCom(@RequestBody SoundComDto soundComDto) {
        log.info("合成自定义声音");
        // 使用复刻的声音来合成文本为语音
        SpeechSynthesisParam param = SpeechSynthesisParam.builder()
                .apiKey(aliOssProperties.getApikey())
                .model("cosyvoice-clone-v1")
                .voice(soundComDto.getModel_id())
                .build();
        SpeechSynthesizer synthesizer = new SpeechSynthesizer();
        ByteBuffer audio = synthesizer.call(param);
        // 保存合成的语音到文件
        System.out.println("TTS RequestId: " + synthesizer.getLastRequestId());
        File file = new File("output.mp3");
        try (FileOutputStream fos = new FileOutputStream(file)) {
            fos.write(audio.array());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return  Result.success();
    }*/
}
